#include <sys/types.h>
#include <stdint.h>
#include "airkiss.h"

#define MAX_MESSAGE		40
#define MESSAGE_SIZE	2
#define MAX_BUF_SIZE	80
#define ETH_ALEN	6

//static uint8_t stored[MAX_BUF_SIZE];
//static uint8_t map[MAX_BUF_SIZE];
//static uint8_t bitmap[MAX_BUF_SIZE>>8];


static uint8_t buf[MAX_BUF_SIZE];
static uint8_t map[40];
static uint8_t mcast_mac[ETH_ALEN] = {0x01, 0x00, 0x5E, 0x00, 0x00, 0x00};

static int pream_cnt = 0;
static int pream_total_cnt = 0;
static int pream_seq = 0;
static int pream_recved = 0;
static int stage = 0;
static uint16_t seqno = 0;
static int start = 0;

#define BASE	18
#define FIRST	21
static int pream[3] = {0};

/* ALL information are all in len */
int airkiss_recv(uint8_t *packet, int len)
{
	uint8_t *p, *da;
	uint16_t fc;	// frame control 
	uint16_t seq;
	int i;
	int pos;
	int final = 0;

	if (!packet || len < 24)
		return 1;

	fc = packet[0] << 8 | packet[1];

	if (!(fc & 0x0800))
		return 1;	// Data

	if ((fc & 0x3) != 0x2)
		return 1;	// FromDS: 1, ToDS: 0

	da = packet + 4;	// DA
	if (memcmp(da, mcast_mac, 3))
		return 1;	// DA should be 01:00:5e

	p = packet + 22;	// sequence control
	seq = (p[1] << 8 | p[0]) >> 4;
	if (seq == seqno)	// seqno the same, ignore
		return 1;

#if 1
	printf("len %d\n", len);
	for (i = 0; i < 32; i++) {
		printf("%02x ", packet[i]);
	}
	printf("\n");
#endif

	// parse da
	if ((da[3] == BASE) || (da[3] == BASE + 1) || (da[3] == BASE + 2)) {
		// may be preamble
		if ((da[3] == da[4]) && (da[4] == da[5])) {
			pream[da[3] - BASE] = 1;
			if (da == 18) {
				if (!start) {
					start = 1;
				} else {
					start = 0;
					final = 1;
				}
			}
		}

		return 0;
	}

	pos = da[3] - FIRST;
	if (pos < 0 ||  pos > 40)
		return 1;
	buf[pos*2] = da[4];
	buf[pos*2 + 1] = da[5];
	map[pos] = 1;

	//for (i = 0; i < 40; i++) {
	//	if (map[i] == 0)
	//		return 1;
	//}

	if (final)
		printf("all message are received\n");

	for (i = 0; i < 80; i++)
		printf("%02x ", buf[i]);
	printf("\n");

	return 0;

}



